﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.Profile;
using MP.Core.Authentication;
using MP.Core.Config;

public partial class Member_Control_Permission : MP.Core.Authentication.Control.AuthenBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        InitAuthen(EnumModules.PERMISSION);

        if (IsEditForce(Request["u"]))
        {
            if (!IsPostBack)
                LoadData();
        }
        else
        {
            this.Visible = false;
        }
    }

    void LoadData()
    {
        if (Membership.GetUser(Request["u"]) != null)
        {
            DataTable roles = MPRoleProvider.CreateInstant().GetAll();
            roles.DefaultView.RowFilter = "IsEnable <> 0";
            if (roles != null && roles.DefaultView.Table.Rows.Count > 0)
            {
                chklstRoles.DataTextField = "RoleName";
                chklstRoles.DataValueField = "RoleName";
                chklstRoles.DataSource = roles.DefaultView;
                chklstRoles.DataBind();

                string[] r = Roles.GetRolesForUser(Request["u"]);
                for (int i = 0; i < chklstRoles.Items.Count; i++)
                {
                    //chklstRoles.Items[i].Selected = false;
                    for (int j = 0; j < r.Length; j++)
                        if (chklstRoles.Items[i].Value == r[j])
                        {
                            chklstRoles.Items[i].Selected = true;
                            break;
                        }
                }
            }
        }
        else
        {
            btnUpdate.Visible = false;
        }
    }

    protected void btnUpdate_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            string user = Request["u"];
            foreach (ListItem item in chklstRoles.Items)
            {
                if (Roles.IsUserInRole(user, item.Value))
                {
                    if (!item.Selected)
                    {
                        Roles.RemoveUserFromRole(user, item.Value);
                    }
                }
                else
                {
                    if (item.Selected)
                        Roles.AddUserToRole(user, item.Value);
                }
            }

            Response.Redirect(Request.RawUrl);
        }
    }
}
